package myfirstgrailsproject

/**
 * These provide a set of g: tags to be used in the gsp's.
 * These tags give you various functions for looking up information from the database.
 * 
 * @author zach
 *
 */
class FunctionalTagLib {

	def findusers = {attrs, body->
		def user = User.findByUsername(attrs.name);
		if (!user){
			out << "FAIL"
		}
		else{
			out << "SUCCESS"
		}
		//out << "&copy; " + attrs.startYear + " - "
		//out << thisYear() + " " + body()
	}

	def numusers = {attrs, body->
		def course = Course.findByTitle(body().toString());
		if (!course){
			out << "0"
		}
		else{
			out << course.usercount()
		}
	}

	def numexercises = {attrs, body->
		def course = Course.findByTitle(body().toString())
		if (!course){
			out << "0"
		}
		else{
			out << course.getExercises().size()
		}
	}

	/*
	 * Displays all courses that the given user teaches or takes
	 */
	def showmycourses = {attrs, body->
		def user = User.findByUsername(attrs.username);

		def courses = Course.findByProfessor(user);
		if (user.student){
			courses = user.courses();
		}

			
		int i=0;
		for (courseInstance in courses){
			//link to courses
			//out << "<tr class=\"${(i % 2) == 0 ? 'odd' : 'even'}\">"
			out << "<tr class=\"${(i % 2) == 0 ? 'odd' : 'even'}\">"

			out << "<td><a href=\"/MyFirstGrailsProject/course/show/"
			out << courseInstance.id;
			out << "\">"
			out << courseInstance.title;
			out << "</a></td>"

			//other info
			out << "<td>"
			out << courseInstance.professor;
			out << "</td><td align=\"center\">"
			out << courseInstance.usercount();
			out << "</td><td align=\"center\">"
			out << courseInstance.getExercises().size();
			out << "</td></tr>"

			i++;
		}
	}
	
	
	def teamsignup = {attrs, body->
		/*def team = Team.findById(attrs.teamid);
		def user = User.findByUsername(attrs.username);
		team.setUsers([team.getUsers(), user]);*/
		boolean display = false;
		if (body().toString().equals("SELF_SELECT") && !attrs.team?.getUsers()?.contains(session?.user)){
			display = true;
			for (int i = 0; i < attrs.team?.getUsers()?.size(); i++){
				if (attrs.team?.getUsers()?.get(i).getUsername().equals(session?.user?.username)){
					display = false;
				}
			}
		}
		if (0){
			out << "<span class=\"button\"><g:actionSubmit controller=\"team\" action=\"teamsignup\" value=\"Sign up for this team\" /></span>"
		}
	}
	
	def registrationview = {attrs, body->
		def course = Course.get(attrs.id);
		out << course.title;
	}
}

